package com.source.hotelbath.fragment;


import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ffcs.network.connect.CustomerError;
import com.ffcs.network.connect.ResponseListener;
import com.ffcs.network.imgdisplayer.ImgLoader;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.source.hotelbath.MainActivity;
import com.source.hotelbath.R;
import com.source.hotelbath.activity.CreateOrderActivity;
import com.source.hotelbath.activity.ForgetActivity;
import com.source.hotelbath.activity.HotelSelectAct;
import com.source.hotelbath.activity.LoginActivity;
import com.source.hotelbath.activity.PrinterActivity;
import com.source.hotelbath.base.BaseFragment;
import com.source.hotelbath.model.GoodsListBean;
import com.source.hotelbath.model.HodelBean;
import com.source.hotelbath.model.OrderGoodsList;
import com.source.hotelbath.model.PostBean;
import com.source.hotelbath.net.CustomerRequestConstants;
import com.source.hotelbath.net.request.HotelListRequest;
import com.source.hotelbath.net.request.OrderSubmitRequest;
import com.source.hotelbath.net.response.HotelListResponse;
import com.source.hotelbath.net.response.LoginBean;
import com.source.hotelbath.popdialog.HotelChooseListener;
import com.source.hotelbath.utils.DateUtils;
import com.source.hotelbath.utils.DialogCallback;
import com.source.hotelbath.utils.ImageUtils;
import com.source.hotelbath.utils.SharedPreferencesUtils;
import com.source.hotelbath.utils.TintDrawable;
import com.source.hotelbath.weight.MyGridviewForScroll;
import com.source.hotelbath.weight.listview.ptr.PtrMaterialHeader;
import com.source.hotelbath.weight.listview.ptr.ptrloadmore.PtrLoadMoreBase;
import com.source.hotelbath.weight.listview.ptr.ptrloadmore.PtrLoadMoreListView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 取布草的界面
 */

public class LinenFragment extends BaseFragment  {

    public static final String TAG = LinenFragment.class.getSimpleName();
    private View mHeaderView;
    private MyGridviewForScroll gv_linen;
    private LinearLayout ll_hotel;
    private MyHotelListener listener;
    private LinenItemAdapter adapter;
    private HotelListResponse hotelListResponse;
    private TextView tv_hotel;
    private LocalBroadcastManager localBroadcastManager;
    private List<GoodsListBean> commonGood=new ArrayList<>();
    private EmpterAdapter adapter1;
    private Button btn_create;
    private String hotelName;
    private int hotelId;
    private EditText tv_message;
    private Button btn_clear;
    private TextView total_num;
    private TextView tv_money;
    private List<GoodsListBean> commonlist=new ArrayList<>();
    private List<GoodsListBean> commonlistA=new ArrayList<>();
    private Gson gson;


    @Override
    protected View createView(LayoutInflater layoutInflater, ViewGroup var2, Bundle var3) {
        View view=layoutInflater.inflate(R.layout.fragment_linen, null);
        findViews(view);
        return view;
    }

    private void findViews(View view) {
        localBroadcastManager = LocalBroadcastManager.getInstance(getContext());
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(CustomerRequestConstants.CHOOSEGOODS);
        myIntentFilter.addAction(CustomerRequestConstants.CHOOSEHOTEL);
        localBroadcastManager.registerReceiver(mReceiver,myIntentFilter);
        LinearLayout ll_header_left= (LinearLayout) view.findViewById(R.id.ll_header_left);
        ll_header_left.setVisibility(View.GONE);
        view.findViewById(R.id.ll_header_right).setVisibility(View.GONE);
        TextView tv_header_title= (TextView) view.findViewById(R.id.tv_header_title);
        tv_header_title.setText("取布草");
        btn_create = (Button) view.findViewById(R.id.btn_create);
        btn_clear = (Button) view.findViewById(R.id.btn_clear);
        btn_create.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        total_num = (TextView) view.findViewById(R.id.total_num);
        tv_money = (TextView) view.findViewById(R.id.tv_money);

        gv_linen = (MyGridviewForScroll) view.findViewById(R.id.gv_linen);
        ll_hotel = (LinearLayout) view.findViewById(R.id.ll_hotel);
        tv_hotel = (TextView) view.findViewById(R.id.tv_hotel);
        tv_message = (EditText) view.findViewById(R.id.tv_message);
        ll_hotel.setOnClickListener(this);
        adapter = new LinenItemAdapter(getActivity(),commonGood,myHandler,commonlistA);
        gv_linen.setAdapter(adapter);
        gson = new Gson();

    }


    @Override
    protected void afterCreate() {
        super.afterCreate();
        //网络请求 这个界面需要返回酒店的列表
        OkGo.<HotelListResponse>get(CustomerRequestConstants.newUrl+CustomerRequestConstants.Hotel_COMMOND)//
                .tag(this)//
                .execute(new DialogCallback<HotelListResponse>(getActivity(),true) {
                    @Override
                    public void onSuccess(Response<HotelListResponse> response) {
                        hotelListResponse=response.body();
                        if (hotelListResponse!=null){
                            SharedPreferencesUtils.saveStringData(getContext(),"hotelList",gson.toJson(hotelListResponse));
                        }

                    }

                    @Override
                    public void onError(Response<HotelListResponse> response) {
                        super.onError(response);

                        Toast.makeText(getContext(),"请求网络失败",Toast.LENGTH_SHORT).show();
                    }

                });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);

        if (view==ll_hotel){

            Intent intent=new Intent(getContext(),HotelSelectAct.class);
            intent.putExtra("TAG","LinenFragment");
            startActivity(intent);

//            if (hotelListResponse!=null && hotelListResponse.getHotelList()!=null&&hotelListResponse.getHotelList().size()>0){
//                if (listener == null) {
//                    listener = new MyHotelListener(getContext(),hotelListResponse.getHotelList(),location);
//                }
//                listener.showTime();
//            }else{
//                Toast.makeText(getContext(),"网络不好暂无酒店可以选择",Toast.LENGTH_SHORT).show();
//            }

        }else if (view==btn_create){

            postData();
        }else if (view==btn_clear){
            commonGood.clear();
            adapter.notifyDataSetChanged();
            commonlist.clear();
            commonlistA.clear();
            prices=new BigDecimal("0");
            sums=0;
            total_num.setText("合计：");
            tv_money.setText("");
            tv_message.setText("");
        }
    }
    private void postData() {
        OrderGoodsList goodsList = new OrderGoodsList();
        List<PostBean> orderGoodsList=new ArrayList<>();
        for (int i=0;i<commonGood.size();i++){
            PostBean bean=new PostBean();
            bean.setGoodsCode(commonGood.get(i).getGoodsCode());
            bean.setGoodsId(commonGood.get(i).getCatId());
            bean.setGoodsName(commonGood.get(i).getGoodsName());
            bean.setImgpath(commonGood.get(i).getGoodsImgpath());
            bean.setNum(commonGood.get(i).getNum());
            bean.setUnitPrice(commonGood.get(i).getWashPrice());
            orderGoodsList.add(bean);
        }
        goodsList.setOrderGoodsList(orderGoodsList);
        goodsList.setRemark(tv_message.getText().toString());
        goodsList.setHotelId(hotelId);
        goodsList.setHotelName(hotelName);

        String order= gson.toJson(goodsList);
        Intent intent=new Intent(getContext(),CreateOrderActivity.class);
        intent.putExtra("goodsList",goodsList);
        intent.putExtra("tv_money",tv_money.getText().toString());
        intent.putExtra("sums",sums);
        startActivity(intent);

    }


    private int location;

    class MyHotelListener extends HotelChooseListener{


        public MyHotelListener(Context context, List<HodelBean> hodelBeanList, int position) {
            super(context, hodelBeanList, position);
        }

        @Override
        public void getItem(String timeStr, int position) {

            hotelName = hotelListResponse.getHotelList().get(position).getHotelName();
            hotelId = hotelListResponse.getHotelList().get(position).getHotelId();
            adapter.addData(hotelId);
            location=position;
            tv_hotel.setText(hotelName);
        }
    }




    private BroadcastReceiver mReceiver  = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (CustomerRequestConstants.CHOOSEGOODS.equals(intent.getAction())){
                //添加集合
                if (intent.getBooleanExtra("isClear",false)){
                    commonGood.clear();
                    adapter.notifyDataSetChanged();
                    commonlist.clear();
                    commonlistA.clear();
                    prices=new BigDecimal("0");
                    sums=0;
                    total_num.setText("合计：");
                    tv_money.setText("");
                    tv_message.setText("");
                }else {
                    commonGood.clear();
                    commonlistA.clear();
                    List<GoodsListBean> commonGoods = intent.getParcelableArrayListExtra("commonGoods");
                    commonlist = intent.getParcelableArrayListExtra("commonlist");
                    commonlistA.addAll(commonlist);
                    commonGood.addAll(commonGoods);
                    adapter.notifyDataSetChanged();
                }
            }else if (CustomerRequestConstants.CHOOSEHOTEL.equals(intent.getAction())){
                hotelName = intent.getStringExtra("hotelName");
                hotelId = intent.getIntExtra("hotelId",0);
                adapter.addData(hotelId);
                tv_hotel.setText(hotelName);
            }
        }
    };
    private BigDecimal prices;
    private int sums;
    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type=msg.what;
            switch (type){
                case 1:   //布草数量有变化
                    prices=new BigDecimal("0");
                    sums=0;
                    for (int i=0;i<commonGood.size();i++){
                        BigDecimal bd=new BigDecimal(commonGood.get(i).getWashPrice());
                        BigDecimal price=TintDrawable.mul(bd,commonGood.get(i).getNum()+"");
                        sums+=commonGood.get(i).getNum();
                        prices= TintDrawable.add(prices,price);
                    }
                    total_num.setText("合计："+sums+"件");
                    tv_money.setText("￥"+prices);

                    break;

            }

            super.handleMessage(msg);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
       localBroadcastManager.unregisterReceiver(mReceiver);
    }

}
